package com.sta.oldman.coder;

import com.sta.oldman.constants.MsgContains;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author: LunBoWang
 * @description: 解码器
 * @date: 2025/5/25 下午7:50
 * @version: 1.0
 */

public class TcpMsgDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> in) throws Exception {
        if (byteBuf.readableBytes() > 9) {
            // 读取帧头
            short header = byteBuf.readShort();
            if (header != MsgContains.HEADER) {
                ctx.close();
                return;
            }
            // 读取控制字
            byte control = byteBuf.readByte();
            // 读取命令字
            byte command = byteBuf.readByte();
            // 读取长度标识
            short len = byteBuf.readShort();
            int readableByteLen = byteBuf.readableBytes();
            if (readableByteLen > len + 3) {
                ctx.close();
                return;
            }
            byte[] body = new byte[len];
            byteBuf.readBytes(body);
            // 计算校验码
            int sum = 0;
            sum += MsgContains.HEADER;
            sum += control;
            sum += command;
            sum += len;
            for (int datum : body) {
                sum += datum;
            }
            sum = sum & 0xFF;
            // 读取校验码
            byte readSum = byteBuf.readByte();
            int temp = readSum & 0xFF;
            if (temp != sum) {
                ctx.close();
                return;
            }
            // 读取帧尾
            short tail = byteBuf.readShort();
            if (tail != MsgContains.TAIL) {
                ctx.close();
                return;
            }
            TcpMsg tcpMsg = new TcpMsg(control, command, len, body, readSum);
            in.add(tcpMsg);
        }
    }
}

